package com.wish.g01.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.g01.base.dto.FactoringDto;
import com.wish.g01.base.entity.*;
import com.wish.g01.base.mapper.JrFactoringMapper;
import com.wish.g01.base.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.g01.base.vo.FactoringDeatilVo;
import com.wish.g01.common.core.text.UUID;
import com.wish.g01.common.core.utils.IdUtils;
import com.wish.g01.common.security.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 租约保理申请表   服务实现类
 * </p>
 *
 * @author hao
 * @since 2022-05-24
 */
@Service
public class JrFactoringServiceImpl extends ServiceImpl<JrFactoringMapper, JrFactoring> implements IJrFactoringService {

    @Autowired
    private ICfContractService iCfContractService;

    @Autowired
    private IFkBusinessCreditService iFkBusinessCreditService;

    @Autowired
    private IFkBusinessCreditSubService iFkBusinessCreditSubService;

    @Autowired
    private IJrProductService iJrProductService;

    @Autowired
    private IJrFactoringDetailService iJrFactoringDetailService;

    @Override
    public boolean addIJrFactoring(FactoringDto factoringDto) {

//        查询商户是否对产品有权限 (合同id 查询商户id 产品id)
        CfContract byId = iCfContractService.getById(factoringDto.getContractId());

        QueryWrapper<FkBusinessCredit> fkBusinessCreditQueryWrapper = new QueryWrapper<>();
        fkBusinessCreditQueryWrapper.eq("business_id", byId.getBusinessId());
        fkBusinessCreditQueryWrapper.eq("credit_staus", 1);


        FkBusinessCredit one = iFkBusinessCreditService.getOne(fkBusinessCreditQueryWrapper);
//        商家未注册,无权限
        if (one == null) {
            return false;
        }

        QueryWrapper<FkBusinessCreditSub> fkBusinessCreditSubQueryWrapper = new QueryWrapper<>();
        fkBusinessCreditSubQueryWrapper.eq("product_id", factoringDto.getJrProductId());
        fkBusinessCreditSubQueryWrapper.eq("credit_id", one.getId());
        FkBusinessCreditSub findById = iFkBusinessCreditSubService.getOne(fkBusinessCreditSubQueryWrapper);
//        产品不在平台上,商户无授权
        if (findById == null) {
            return false;
        }
//        授信子表
        FkBusinessCreditSub fkBusinessCreditSub = new FkBusinessCreditSub();
        BeanUtils.copyProperties(findById, fkBusinessCreditSub);

        BigDecimal subtractProduct = BigDecimal.ZERO;
        System.err.println("输出bigDecimal" + subtractProduct);
        //产品剩余可用授信额度 该产品总授信额度减去该产品已用授信额度
        if (findById.getUsedCreditline() != null && !findById.getUsedCreditline().equals(BigDecimal.ZERO)) {
            subtractProduct = findById.getTotalCreditline().subtract(findById.getUsedCreditline());
        } else {
            subtractProduct = findById.getTotalCreditline();
        }

        //传过来的.应收租约合计金额大于该产品剩余授信金额
        if (factoringDto.getRentMoney().compareTo(subtractProduct) == 1) {
//            msgResult.setMsgInfo("授信额度不足，请联系维数公寓客服：400-008-3363");
            return false;
        }

        //剩余月度授信额度 该产品月度授信额度减去该产品月度已用授信额度
        if (findById.getMonthlyTotalCreditline() != null && !findById.getMonthlyTotalCreditline().equals(BigDecimal.ZERO)) {
            //总授信额度减去已用授信额度
            BigDecimal subtractMonthly = BigDecimal.ZERO;
            if (findById.getMonthlyUsedCreditline() != null && !findById.getMonthlyUsedCreditline().equals(BigDecimal.ZERO)) {
                subtractMonthly = findById.getMonthlyTotalCreditline().subtract(findById.getMonthlyUsedCreditline());
            } else {
                subtractMonthly = findById.getMonthlyTotalCreditline();
            }
            //传过来的应收租约合计金额大于该商户月剩余授信金额
            if (factoringDto.getRentMoney().compareTo(subtractMonthly) == 1) {
//                msgResult.setMsgInfo("授信额度不足，请联系维数公寓客服：400-008-3363");
                return false;
            }
            fkBusinessCreditSub.setMonthlyTotalCreditline(subtractMonthly);
        }
        fkBusinessCreditSub.setUsedCreditline(subtractProduct);
//        修改风控子表中的,产品可使用的授信额度
        iFkBusinessCreditSubService.saveOrUpdate(fkBusinessCreditSub);

        //       增加租约保理申请表
        JrFactoring jrFactoring = new JrFactoring();
        BeanUtils.copyProperties(factoringDto, jrFactoring);
        jrFactoring.setBusinessId(byId.getBusinessId().toString());

//        租约保理申请单号
        String order = UUID.randomUUID().toString();
        jrFactoring.setFactoringOrderNo(order);
//        外部合同号
        jrFactoring.setOutOrderNo(byId.getOutContractNo());

        JrProduct product = iJrProductService.getById(factoringDto.getJrProductId());
//        资方id和姓名
        jrFactoring.setCapitalId(product.getCompanyId());
        jrFactoring.setCapitalName(product.getCompanyName());

//         审核状态
        jrFactoring.setApplyState(1);
        jrFactoring.setDelFlg(false);
//        创建用户和更新用户(不为空)
        jrFactoring.setCreateUserid(SecurityUtils.getUserId());
        jrFactoring.setCreateTime(LocalDateTime.now());
        jrFactoring.setUpdateUserid(SecurityUtils.getUserId());
        jrFactoring.setUpdateTime(LocalDateTime.now());
//        借款金额
        jrFactoring.setLoanAmount(factoringDto.getFactoringCreditMoney());
//        增加租约保理申请表
        boolean save = save(jrFactoring);

//        增加租约保理的详情
        JrFactoringDetail jrFactoringDetail = new JrFactoringDetail();
        BeanUtils.copyProperties(byId,jrFactoringDetail);
//        租约保理id
        jrFactoringDetail.setFactoringId(jrFactoring.getId());
//        商户id
        jrFactoringDetail.setBusinessId(byId.getBusinessId());

//      出房合同id
        jrFactoringDetail.setCfContractId(factoringDto.getContractId());

//        jrFactoringDetail.setHouseId(byId.getHouseId());
//        应收租约
         jrFactoringDetail.setShouldMonthRent(factoringDto.getRentMoney());
//         保理授信额度
         jrFactoringDetail.setFactoringCreditMoney(factoringDto.getFactoringCreditMoney());
//      服务费
          jrFactoringDetail.setServiceFee(factoringDto.getServiceFee());
//      保理利息
        jrFactoringDetail.setFactoringInterest(factoringDto.getFactoringAdditionalMoney());
//        周期
        jrFactoringDetail.setFactoringPeriod(factoringDto.getMonthLimit());

        List<FactoringDeatilVo> jrFactoringDetailList = factoringDto.getJrFactoringDetailList();

        jrFactoringDetailList.forEach(item->{
            System.out.println("1111111"+item.getBorrowedStart());
            jrFactoringDetail.setBorrowedStart(item.getBorrowedStart());
            jrFactoringDetail.setBorrowedEnd(item.getBorrowedEnd());
        });
        iJrFactoringDetailService.save(jrFactoringDetail);
        System.out.println("222"+save);
        return save;



    }
}
